<template>
  <!-- 用户表单对话框 -->
  <zy-base-dialog
    :title="dialogTitle"
    v-model:visible="dialogVisible"
    v-model:fullscreen="dialogFullscreen"
    width="600px"
    :close-on-click-modal="false"
    @close="handleDialogClose"
    @cancel="handleDialogClose"
    @submit="handleSubmit"
    :submit-loading="submitLoading"
  >
    <el-form
      ref="userFormRef"
      :model="userForm"
      :rules="userFormRules"
      label-width="100px"
      label-position="right"
    >
      <el-form-item label="用户名" prop="userName">
        <el-input v-model="userForm.userName" placeholder="请输入用户名" />
      </el-form-item>
      <el-form-item label="登录账号" prop="loginName">
        <el-input v-model="userForm.loginName" placeholder="请输入登录账号" />
      </el-form-item>
      <el-form-item label="密码" prop="password" v-if="!userForm.userId">
        <el-input
          v-model="userForm.password"
          type="password"
          placeholder="请输入密码"
          show-password
        />
      </el-form-item>
      <el-form-item label="手机号码" prop="phone">
        <el-input v-model="userForm.phone" placeholder="请输入手机号码" />
      </el-form-item>
      <el-form-item label="电子邮箱" prop="email">
        <el-input v-model="userForm.email" placeholder="请输入电子邮箱" />
      </el-form-item>
    </el-form>
  </zy-base-dialog>
</template>

<script setup lang="ts">
import { ref, reactive, watch } from 'vue'
import { ElMessage, ElForm, ElFormItem, ElInput } from 'element-plus'
import type { FormInstance, FormRules } from 'element-plus'
import { addUser, updateUser, SysUser } from '@/api/system/user'
// Business 组件已全局注册，无需导入
import { isResponseSuccess } from '@/utils/httpStatus'

// Props
interface Props {
  visible: boolean
  userData?: SysUser
  isEdit?: boolean
}

const props = withDefaults(defineProps<Props>(), {
  visible: false,
  userData: undefined,
  isEdit: false
})

// Emits
const emit = defineEmits<{
  'update:visible': [value: boolean]
  success: []
}>()

// 响应式数据
const dialogVisible = ref(false)
const dialogTitle = ref('')
const submitLoading = ref(false)
const dialogFullscreen = ref(false)

const userFormRef = ref<FormInstance>()

// 用户表单
const userForm = reactive<SysUser>({
  userId: undefined,
  userName: '',
  loginName: '',
  password: '',
  phone: '',
  email: '',
  passwordExpirationDate: undefined,
  systemCode: '',
  isLock: 0
})

// 表单验证规则
const userFormRules: FormRules = {
  userName: [
    { required: true, message: '请输入用户名', trigger: 'blur' },
    { min: 2, max: 20, message: '用户名长度在 2 到 20 个字符', trigger: 'blur' }
  ],
  loginName: [
    { required: true, message: '请输入登录账号', trigger: 'blur' },
    { min: 3, max: 20, message: '登录账号长度在 3 到 20 个字符', trigger: 'blur' }
  ],
  password: [
    { required: true, message: '请输入密码', trigger: 'blur' },
    { min: 6, max: 20, message: '密码长度在 6 到 20 个字符', trigger: 'blur' }
  ],
  phone: [{ pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号码', trigger: 'blur' }],
  email: [{ type: 'email', message: '请输入正确的邮箱地址', trigger: 'blur' }],
  passwordExpirationDate: [{ type: 'date', message: '请选择密码过期时间', trigger: 'change' }],
  systemCode: [{ required: true, message: '请输入系统编码', trigger: 'blur' }]
}

// 监听 visible 变化
watch(
  () => props.visible,
  (newVal) => {
    dialogVisible.value = newVal
    if (newVal) {
      dialogTitle.value = props.isEdit ? '编辑用户' : '新增用户'
      if (props.isEdit && props.userData) {
        Object.assign(userForm, props.userData)
      } else {
        resetUserForm()
      }
    }
  },
  { immediate: true }
)

// 监听 dialogVisible 变化，同步到父组件
watch(dialogVisible, (newVal) => {
  emit('update:visible', newVal)
})

// 提交表单
const handleSubmit = async () => {
  if (!userFormRef.value) return

  try {
    await userFormRef.value.validate()
    submitLoading.value = true

    let result
    if (userForm.userId) {
      result = await updateUser(userForm)
      if (isResponseSuccess(result)) {
        ElMessage.success('更新成功')
        dialogVisible.value = false
        emit('success')
      } else {
        ElMessage.error('更新失败')
      }
    } else {
      result = await addUser(userForm)
      if (isResponseSuccess(result)) {
        ElMessage.success('新增成功')
        dialogVisible.value = false
        emit('success')
      } else {
        ElMessage.error('新增失败')
      }
    }
  } catch (error) {
    console.error('提交失败:', error)
    ElMessage.error('提交失败')
  } finally {
    submitLoading.value = false
  }
}

// 重置用户表单
const resetUserForm = () => {
  Object.assign(userForm, {
    userId: undefined,
    userName: '',
    loginName: '',
    password: '',
    phone: '',
    email: '',
    passwordExpirationDate: undefined,
    systemCode: '',
    isLock: 0
  })
}

// 对话框关闭
const handleDialogClose = () => {
  resetUserForm()
  if (userFormRef.value) {
    userFormRef.value.resetFields()
  }
}
</script>

<style lang="less" scoped>
.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 8px;
}
</style>
